package com.jiangyg.mall.authz.controller;

import com.jiangyg.mall.authz.service.CaptchaService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 类描述：验证码控制器
 *
 * @author jiangyg
 * @date 2022-01-06
 */
@RestController
public class CaptchaController {

    /**
     * 验证码
     */
    private final CaptchaService captchaService;

    @Autowired
    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    /**
     * 功能描述：获取验证码图片
     *
     * @param response 响应
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, @RequestParam("uuid") String uuid) throws IOException {
        // 1. 设置请求参数和文件扩展名
        response.setHeader("uuid", uuid);
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 2. 生成图片验证码，并返回前端
        final BufferedImage image = captchaService.createCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
